package com.wangzhixuan.commons.shiro;

import com.wangzhixuan.commons.exception.BussinessException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

/**
 * Shiro工具类
 *
 * @author lixin
 * @since 2019-2-14
 */
public class ShiroUtils {
    /**
     * 加密算法
     */
    final static String HASH_ALGORITHM_NAME = "SHA-256";
    /**
     * 循环次数
     */
    final static int HASH_ITERATIONS = 16;


    private static ShiroUser getShiroUser() {
        Object obj = getSubject().getPrincipal();
        if (obj != null) {
            ShiroUser user = new ShiroUser();
            if (obj instanceof ShiroUser) {
                user = (ShiroUser) obj;
            } else {
                BeanUtils.copyProperties(SecurityUtils.getSubject().getPrincipal(), user);
            }
            return user;
        }
        return null;
    }

    /**
     * 获取登录用户信息，未登录时为null
     *
     * @return 用户信息
     */
    public static ShiroUser getUserWithNull() {
        return getShiroUser();
    }

    public static String sha256(String password, String salt) {
        return new SimpleHash(HASH_ALGORITHM_NAME, password, salt, HASH_ITERATIONS).toString();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取登录用户信息，未登录时抛出异常
     *
     * @return 用户信息
     */
    public static ShiroUser getUser() {
        ShiroUser user = getShiroUser();
        if (user != null) {
            return user;
        }
        throw new BussinessException("未登录");
    }

    public static Long getUserId() {
        return getUser().getId();
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }


}

